/*
 * @FilePath: dict.controller.js
 * @Author: 'Giovan'
 * @Date: 2024-01-23 10:37:31
 * @LastEditors: Giovan
 * @LastEditTime: 2024-01-24 15:21:15
 */
const db = require("../models");
const logger = require("../utils/utils.logger");
const DAO = require("../dao/DAO");
const { where } = require("sequelize");
const Dict = db.dict;
const DictVal = db.dictVal;
const Op = db.Op;

// Create and Save a new Dict
exports.create = (req, res) => {
    const pm = req.body;
    if (!pm.name) return res.sendResultAto(null, 605, '字典名不能为空')
    if (!pm.dict) return res.sendResultAto(null, 605, '字典值不能为空')
    console.log(pm);
    const dict = {
        name: pm.name,
        dict: pm.dict,
    };
    Dict.findOne({ where: { 'name': pm.name, 'dict': pm.dict } }).then(singleDict => {
        if (singleDict && singleDict.id) return res.sendResultAto(null, 605, '该字典已存在！')
        DAO.create(Dict, dict, data => {
            res.sendResult(data)
        })
    })
};

exports.getDict = (req, res) => {
    const pm = req.body;
    Dict.findOne({ where: { 'dict': pm.name } }).then(data => {
        if (data) {
            let sql = `SELECT \`key\`, value FROM mg_dict_val WHERE dictId = ?;`
            let values = [data.id];
            DAO.doQuery1(sql, values, (list) => {
                res.sendResult({ data: list.data[0], code: 200, message: '获取成功！' })
            })
        } else {
            res.sendResult({ data: null, code: 200, message: '暂无该字典' })

        }

    })
};
// Retrieve all Dict from the database.
exports.findAll = (req, res) => {
    const pm = req.body;
    DAO.list(Dict, pm, list => {
        res.sendResult(list)
    })
};

// Find a single Dict with an id
exports.findOne = (req, res) => {
    const pm = req.body;
    DAO.findOne(Dict, pm, data => {
        res.sendResult(data)
    })
};

// Update a Dict by the id in the request
exports.update = (req, res) => {
    const pm = req.body;
    // 请求验证
    DAO.update(Dict, pm, { id: pm.id }, data => {
        res.sendResult(data)
    })

};

// Delete a Dict with the specified id in the request
exports.delete = (req, res) => {
    const pm = req.body;
    // 请求验证
    if (!pm.id) return res.sendResult({ data: '', code: 605, message: "ID不能为空！" })
    DAO.delete(Dict, { id: pm.id }, data => {
        res.sendResult(data)
    })

};



